//
//  InformationViewController.m
//  TLS
//
//  Created by newtouch on 15/8/16.
//  Copyright (c) 2015年 tulin. All rights reserved.
//

#import "InformationViewController.h"
#import "informationTableViewCell.h"
#import "JSONKit.h"
#import "InfomationTextFTableViewCell.h"
@interface InformationViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource>{
    NSString *cellName;
    NSString *textCellName;
    NSInteger tagTextF;
    NSString *cuText;
    NSString *currentPlaceholder;
}
@property (nonatomic, strong) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;
@property (nonatomic, strong) NSArray *dataAry;
@property (nonatomic, strong) NSMutableDictionary * dataDic;
@property (nonatomic, strong) UIPickerView *pickerView;

@property (nonatomic, strong) NSArray *pickerData;
@end

@implementation InformationViewController

- (UIPickerView *)pickerView{
    
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 216)];
        _pickerView.delegate = self;
        _pickerView.dataSource =self;
        _pickerView.backgroundColor = [UIColor whiteColor];
    }
    
    return _pickerView;
}

- (NSMutableDictionary *)dataDic{

    if (!_dataDic) {
        _dataDic = [NSMutableDictionary dictionary];
    }
    return _dataDic;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getCountryList];
    
    textCellName = NSStringFromClass([InfomationTextFTableViewCell class]);
    cellName = NSStringFromClass([informationTableViewCell class]);
    
    [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([informationTableViewCell class]) bundle:nil] forCellReuseIdentifier:cellName];
    [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([InfomationTextFTableViewCell class]) bundle:nil] forCellReuseIdentifier:textCellName];
    
    self.navigationItem.title = [self.informationType isEqualToString:@"Account"] ? @"Account Information" : @"Company Information";
    if ([self.informationType isEqualToString:@"Account"]) {
        self.submitBtn.hidden = YES;
    }
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self getInformation];
    
}

- (void)loadDataWithDic:(NSDictionary *)dic{

    if ([self.informationType isEqualToString:@"Account"]) {
        NSString *name = dic[@"name"];
        NSArray *arrName = [name componentsSeparatedByString:@" "];
        _dataAry = @[@{@"title":@"First Name",@"value":vailable(arrName[0])},
                     @{@"title":@"Last Name",@"value":vailable(arrName[1])},
                     @{@"title":@"Email",@"value":vailable(dic[@"email"])}];
    }else{

        _dataAry = @[@{@"title":@"Company Name",@"value":vailable(dic[@"company"])},
                     @{@"title":@"Phone Number",@"value":vailable(dic[@"phone"])},
                     @{@"title":@"Fax Number",@"value":vailable(dic[@"fax"])},
                     @{@"title":@"Address",@"value":vailable(dic[@""])},
                     @{@"title":@"Address2",@"value":vailable(dic[@""])},
                     @{@"title":@"City",@"value":vailable(dic[@"city"])},
                     @{@"title":@"State",@"value":vailable(dic[@"state"])},
                     @{@"title":@"Country",@"value":vailable(dic[@"country"])},
                     @{@"title":@"Zipcode",@"value":vailable(dic[@"zipcode"])},
                     @{@"title":@"Federal Tax ID",@"value":vailable(dic[@"taxID"])},
                     @{@"title":@"Sales Representative",@"value":vailable(dic[@""])},
                     @{@"title":@"Office",@"value":vailable(dic[@""])}];
        

    }
    
    [self.tableView reloadData];
}

#pragma mark -  UITableViewDataSource,UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _dataAry.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dic = _dataAry[indexPath.row];
    
    if ([self.informationType isEqualToString:@"Account"]) {
        informationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName forIndexPath:indexPath];
        cell.titleStr.text = vailable(dic[@"title"]);
        cell.valueStr.text = vailable(dic[@"value"]);
        cell.valueStr.userInteractionEnabled = NO;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        InfomationTextFTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:textCellName];
        cell.textFeilld.delegate = self;
        cell.textFeilld.text = vailable(dic[@"value"]);
        if (indexPath.row == 7) {
            cell.textFeilld.inputView = self.pickerView;
        }
        cell.textFeilld.placeholder = vailable(dic[@"title"]);
        cell.textFeilld.tag = indexPath.row;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
   
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}



#pragma mark - UITextFiledDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    currentPlaceholder = textField.placeholder;
    textField.placeholder = @"";
    
    if (textField.tag == 7) {
        textField.text = self.pickerData[0];
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    textField.placeholder = currentPlaceholder;

}



//mobile.ltsecurityinc.com/api3/customers/info?id=8127

- (void)getInformation{
    
    NSDictionary *dic = @{@"customerid":mAvailableString([HomeShareInfo sharedHomeInfoModel].userInfo.customerid)};
    
    [self.view showProgressHUDWithInfo:alert_Loading];
    [Networking GetAFNRequestWithParameters:dic andHttpType:@"customers" action:@"info" withSuccessBlock:^(id dicResult) {
        NSLog(@"请求成功:%@",dicResult);
        [self.view hiddenProgressHUD];
        NSDictionary *dic = [dicResult[@"data"] firstObject];
        [self loadDataWithDic:dic];
        
    } withErrorBlock:^(id dicResult, NSString *error) {
        [self.view hiddenProgressHUD];
        NSLog(@"请求失败:%@",dicResult);
        [self.view alertViewShowWithMessage:dicResult[@"message"] View:self.navigationController.view];
    }];

}

- (void)requestChangeInfo{

//   //mobile.ltsecurityinc.com/api2/customers/update1?customerid=10877&data={"email":"584189088@qq.com","firstname":"li","lastname":"joelean","street":"California","postcode":"123456","city":"hangzhou","country_id":"US"}
    NSArray *nameArr = [self.dataDic[@"name"] componentsSeparatedByString:@" "];
    NSString *firstName = nameArr[0];
    NSString *lastName = nameArr[1];
    
    InfomationTextFTableViewCell *streetCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    InfomationTextFTableViewCell *codeCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:8 inSection:0]];
     InfomationTextFTableViewCell *cityCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0]];
     InfomationTextFTableViewCell *countryCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:7 inSection:0]];
    
    NSDictionary *dataDic = @{@"email":mAvailableString(self.dataDic[@"email"]),
                              @"firstname":mAvailableString(firstName),
                              @"lastname":mAvailableString(lastName),
                              @"street":mAvailableString(streetCell.textFeilld.text),
                              @"postcode":mAvailableString(codeCell.textFeilld.text),
                              @"city":mAvailableString(cityCell.textFeilld.text),
                              @"country_id":mAvailableString(countryCell.textFeilld.text)};
    
    // 字典转 json 字符串
    NSError *praseError = nil;
    NSData * data = [NSJSONSerialization dataWithJSONObject:dataDic options:NSJSONWritingPrettyPrinted error:&praseError];
    NSString * dicStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSDictionary *dic = @{@"customerid":mAvailableString([HomeShareInfo sharedHomeInfoModel].userInfo.customerid),
                          @"data":mAvailableString(dicStr)};
    
    [self.view showProgressHUDWithInfo:alert_Loading];

    [Networking GetAFNRequestWithParameters:dic andHttpType:@"customers" action:@"update1" withSuccessBlock:^(id dicResult) {
        NSLog(@"请求成功:%@",dicResult);
        [self.view hiddenProgressHUD];
        
        [self.view alertViewShowWithMessage:@"Update Successful" View:self.navigationController.view];

    } withErrorBlock:^(id dicResult, NSString *error) {
        [self.view hiddenProgressHUD];
        NSLog(@"请求失败:%@",dicResult);
        [self.view alertViewShowWithMessage:dicResult[@"message"] View:self.navigationController.view];
        
    }];
    
}


- (void)getCountryList{
//mobile.ltsecurityinc.com/api2/customers/getcountry
    [Networking GetAFNRequestWithParameters:@{} andHttpType:@"customers" action:@"getcountry" withSuccessBlock:^(id dicResult) {
        NSLog(@"请求成功:%@",dicResult);
        id data = [dicResult[@"data"] firstObject];
        
        if ([data count] != 0){
            if ([data isKindOfClass:[NSDictionary class]]) {
                self.pickerData = [self sortArrayWithDic:data];
            }else if([data isKindOfClass:[NSArray class]]){
                self.pickerData= data;
            }
        }
        [self.pickerView reloadAllComponents];
        
    } withErrorBlock:^(id dicResult, NSString *error) {
        NSLog(@"请求失败:%@",dicResult);
        
        id data = [dicResult[@"data"] firstObject];
        
        if ([data count] != 0){
            if ([data isKindOfClass:[NSDictionary class]]) {
                self.pickerData = [self sortArrayWithDic:data];
            }else if([data isKindOfClass:[NSArray class]]){
                self.pickerData = data;
            }
        }
        [self.pickerView reloadAllComponents];
    }];

}

- (NSArray *)sortArrayWithDic:(NSDictionary *)dic{
    NSMutableArray *arr = [NSMutableArray array];
    NSArray *allKeys = [dic allKeys];
    for (int i = 1; i < allKeys.count; i ++) {
       
        for (NSString *key in allKeys) {
            if ([key integerValue] == i) {
                
                [arr addObject:dic[key]];
            }
        }
        
    }
    
    return arr;

}
- (IBAction)submitAction:(UIButton *)sender {
    
    
    [self requestChangeInfo];
    
}


#pragma mark - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    return self.pickerData.count;

}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{

    return self.pickerData[row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    InfomationTextFTableViewCell *countryCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:7 inSection:0]];
    countryCell.textFeilld.text = self.pickerData[row];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
